package org.example.week10.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DBUtil {
    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    // 静态代码块，用于加载配置文件
    static {
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("db-config");
            driver = bundle.getString("DRIVER");
            url = bundle.getString("URL");
            user = bundle.getString("USER");
            password = bundle.getString("PASSWORD");

            // 加载数据库驱动
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取数据库连接
     * @return 数据库连接对象
     * @throws SQLException 如果连接失败
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
    //可以直接调用

    /**
     * 关闭数据库连接
     * @param connection 数据库连接对象
     */
    public static void closeConnection(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

